package com.easymin.weixin;


import com.easymin.weixin.entity.Admin;
import com.easymin.weixin.manager.AdminManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.security.Principal;

import javax.annotation.PostConstruct;

/**
 * 用户认证.
 *
 * @author Shine
 */
@SuppressWarnings("all")
public class AuthenticationRealm extends AuthorizingRealm {

  @Autowired
  private AdminManager adminManager;


  @PostConstruct
  public void initCredentialsMatcher() {
    HashedCredentialsMatcher cm = new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME);
    setCredentialsMatcher(cm);
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
   * .shiro.subject.PrincipalCollection)
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {

    Principal principal = (Principal) pc.fromRealm(getName()).iterator().next();


    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();


    return authorizationInfo;
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org
   * .apache.shiro.authc.AuthenticationToken)
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {

    ValidateToken authenticationToken = (ValidateToken) token;

    // 验证用户
    String username = authenticationToken.getUsername();
    String password = new String(authenticationToken.getPassword());

    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { // 验证用户名密码是否为空

      throw new UnknownAccountException();
    }

    Admin admin = adminManager.findByUsername(username);

    if (null == admin) { // 验证用户是否存在
      throw new UnknownAccountException();
    }


    Sha256Hash sha256Hash = new Sha256Hash(password);

    if (admin.getPassword().equals(sha256Hash.toBase64())) { // 密码匹配

      Principal principal = new ShiroPrincipal(admin.getId(), admin.getUsername());

      return new SimpleAuthenticationInfo(principal, Base64.decode(admin.getPassword()), getName());

    } else {
      throw new IncorrectCredentialsException();
    }

  }

}
